"""
使用示例：如何解析和使用GDF文件数据
"""

from parse_gdf import parse_gdf_file, extract_data_from_gdf
import numpy as np
import matplotlib.pyplot as plt


def example_basic_parsing():
    """示例1: 基本解析"""
    print("="*60)
    print("示例1: 基本解析GDF文件")
    print("="*60)
    
    # 解析一个文件
    file_path = "A01T.gdf"  # 训练数据
    raw, info = parse_gdf_file(file_path)
    
    if raw is not None:
        print(f"\n成功解析文件: {file_path}")
        print(f"可以访问原始数据: raw.get_data()")
        print(f"数据形状: {raw.get_data().shape}")


def example_extract_data():
    """示例2: 提取特定时间段的数据"""
    print("\n" + "="*60)
    print("示例2: 提取特定时间段的数据")
    print("="*60)
    
    file_path = "A01T.gdf"
    
    # 提取前10秒的数据
    data, channel_names, sfreq, times = extract_data_from_gdf(
        file_path, 
        start_time=0, 
        stop_time=10
    )
    
    print(f"\n提取的数据:")
    print(f"  数据形状: {data.shape}")
    print(f"  通道: {len(channel_names)} 个")
    print(f"  采样频率: {sfreq} Hz")
    print(f"  时间长度: {times[-1] - times[0]:.2f} 秒")
    
    # 可以选择特定通道
    if len(channel_names) > 0:
        channel_idx = 0
        channel_data = data[channel_idx, :]
        print(f"\n  通道 '{channel_names[channel_idx]}' 的数据:")
        print(f"    前10个采样点: {channel_data[:10]}")
        print(f"    均值: {channel_data.mean():.4f}")
        print(f"    标准差: {channel_data.std():.4f}")


def example_plot_signal():
    """示例3: 绘制信号（需要matplotlib）"""
    print("\n" + "="*60)
    print("示例3: 绘制信号")
    print("="*60)
    
    try:
        import matplotlib.pyplot as plt
        
        file_path = "A01T.gdf"
        
        # 提取前5秒的数据
        data, channel_names, sfreq, times = extract_data_from_gdf(
            file_path, 
            start_time=0, 
            stop_time=5
        )
        
        # 绘制前3个通道的信号
        n_channels_to_plot = min(3, len(channel_names))
        
        fig, axes = plt.subplots(n_channels_to_plot, 1, figsize=(12, 2*n_channels_to_plot))
        if n_channels_to_plot == 1:
            axes = [axes]
        
        for i in range(n_channels_to_plot):
            axes[i].plot(times, data[i, :])
            axes[i].set_title(f"通道: {channel_names[i]}")
            axes[i].set_xlabel("时间 (秒)")
            axes[i].set_ylabel("幅值")
            axes[i].grid(True)
        
        plt.tight_layout()
        plt.savefig("signal_plot.png", dpi=150)
        print(f"\n已保存信号图到: signal_plot.png")
        print(f"注意: 如果要在Jupyter中显示，使用 plt.show()")
        
    except ImportError:
        print("\nmatplotlib未安装，跳过绘图示例")
        print("安装方法: pip install matplotlib")


if __name__ == "__main__":
    # 运行示例
    example_basic_parsing()
    example_extract_data()
    example_plot_signal()

